import { createStore } from 'vuex'
import axios from 'axios'

const store = createStore({
  state() {
    return {
      sellerInfo: {},
      goods: [],
      carList: [],
    }
  },
  getters: {
    cartList(state){
      const arr=[];
      state.goods.forEach(( item )=>{
        item.foods.forEach(( food )=>{
          if( food.count !== undefined && food.count > 0 ){
            arr.push( food );
          }
        });
      });
      return arr;
    }
  },
  mutations: {
    setSeller(state, payload) {
      console.log(payload)
      state.sellerInfo = payload.data
    },
    setGoods(state, payload) {
      state.goods = payload.data
    },
    setCarList(state, payload) {
      const hasItem = state.carList.findIndex((item) => {
        return item.name == payload.item.name
      })
      if (hasItem == '-1') {
        state.carList.push(payload.item)
        // console.log(state.carList);
      }
    },
  },
  actions: {
    async getSeller({ commit }) {
      const {
        data: { data },
      } = await axios.get('/api/seller')
      // console.log("---------------")
      commit('setSeller', {
        data,
      })
    },
    async getGoods({ commit }) {
      const {
        data: { data },
      } = await axios.get('/api/goods')
      commit('setGoods', {
        data,
      })
    },
  },
})

export default store
